package com.erf.message;

import com.erf.tools.SequenceUtil;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.nio.charset.StandardCharsets;

/**
 * @author zhangzy
 * @date 2022/7/5
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = false)
public class LoginRequest extends BaseMessage {
    private int nameLength;
    private String name;
    private int passwordLength;
    private String password;

    public LoginRequest(String name, String password) {
        this.name = name;
        this.password = password;
    }

    @Override
    public void encode(ByteBuf byteBuf) {
        //初始化
        byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
        this.nameLength = nameBytes.length;
        byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8);
        this.passwordLength = passwordBytes.length;
        //赋值
        byteBuf.writeInt(12 + 4 + nameLength + 4 + passwordLength);
        byteBuf.writeInt(0x00000001);
        byteBuf.writeInt(SequenceUtil.getSequenceId());
        byteBuf.writeInt(nameLength);
        byteBuf.writeBytes(nameBytes);
        byteBuf.writeInt(passwordLength);
        byteBuf.writeBytes(passwordBytes);
    }

    @Override
    public BaseMessage decode(int length, int command, int sequence, ByteBuf body) {
        //初始化报文头
        this.setLength(length);
        this.setCommand(command);
        this.setSequence(sequence);
        //初始化包体属性
        this.nameLength = body.readInt();
        CharSequence userName = body.readCharSequence(nameLength, StandardCharsets.UTF_8);
        this.name = userName.toString();
        this.passwordLength = body.readInt();
        CharSequence password = body.readCharSequence(passwordLength, StandardCharsets.UTF_8);
        this.password = password.toString();
        return this;
    }

}
